import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:chewie/chewie.dart';
import 'package:video_player/video_player.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../core/media_control_event_bus.dart';

class NbaVideoPlayer extends StatefulWidget {
  final String vid;
  final String title;
  final Map<String, dynamic>? videoData;
  final double aspectRatio;

  const NbaVideoPlayer({
    super.key,
    required this.vid,
    required this.title,
    this.videoData,
    this.aspectRatio = 16 / 9,
  });

  @override
  State<NbaVideoPlayer> createState() => _NbaVideoPlayerState();
}

class _NbaVideoPlayerState extends State<NbaVideoPlayer> {
  VideoPlayerController? _videoController;
  ChewieController? _chewieController;
  bool _isPlaying = false;
  bool _showThumbnail = true;
  String _currentQuality = 'shd'; // 默认清晰度
  List<Map<String, dynamic>> _qualities = []; // 可用清晰度列表
  bool _isFullScreen = false;
  String? _currentVideoUrl;
  bool _isLiveStream = false;
  double _currentVolume = 1.0;
  bool _isMuted = false;
  bool _showControls = true;
  Timer? _controlsTimer;
  
  // 媒体控制事件监听器
  MediaControlListener? _mediaControlListener;

  @override
  void initState() {
    super.initState();
    _loadVideoThumbnail();
    _initializeQualities();
    _setupMediaControlListener();
  }

  void _initializeQualities() {
    // 从视频数据中获取清晰度选项，如果没有则使用默认值
    if (widget.videoData != null && widget.videoData!['qualities'] != null) {
      final qualities = widget.videoData!['qualities'] as List<dynamic>;
      _qualities = qualities.map((q) => {
        'name': q['name']?.toString() ?? '',
        'sname': q['sname']?.toString() ?? ''
      }).toList();
    } else {
      // 默认清晰度选项
      _qualities = [
        {'name': 'shd', 'sname': '超清'},
        {'name': 'hd', 'sname': '高清'},
        {'name': 'sd', 'sname': '标清'}
      ];
    }
  }

  Future<void> _changeQuality(String quality) async {
    if (_currentQuality == quality) return;
    
    setState(() {
      _currentQuality = quality;
    });
    
    // 如果视频正在播放，重新初始化播放器
    if (_isPlaying) {
      await _reinitializeVideoPlayer();
    }
  }

  Future<void> _reinitializeVideoPlayer() async {
    if (_videoController != null) {
      await _videoController!.dispose();
    }
    if (_chewieController != null) {
       _chewieController!.dispose();
    }
    
   setState(() {
      _videoController = null;
      _chewieController = null;
    });
    
    await _initializeVideoPlayer();
  }

  void _loadVideoThumbnail() {
    // 视频数据中包含缩略图信息，先显示缩略图
    setState(() {
      _showThumbnail = true;
    });
  }

  /// 设置媒体控制事件监听器
  void _setupMediaControlListener() {
    _mediaControlListener = (MediaControlEvent event) {
      if (_videoController == null || !_videoController!.value.isInitialized) {
        return;
      }

      switch (event) {
        case MediaControlEvent.playPause:
          _handlePlayPause();
          break;
        case MediaControlEvent.stop:
          _handleStop();
          break;
        case MediaControlEvent.rewind:
          _handleRewind();
          break;
        case MediaControlEvent.fastForward:
          _handleFastForward();
          break;
        case MediaControlEvent.volumeUp:
          _handleVolumeUp();
          break;
        case MediaControlEvent.volumeDown:
          _handleVolumeDown();
          break;
        case MediaControlEvent.mute:
          _handleMute();
          break;
        case MediaControlEvent.nextTrack:
        case MediaControlEvent.previousTrack:
          // 对于NBA视频，下一曲/上一曲可以处理为下一个/上一个视频
          debugPrint('切换视频功能暂未实现');
          break;
      }
    };
    
    MediaControlEventBus.instance.addListener(_mediaControlListener!);
  }

  /// 移除媒体控制事件监听器
  void _removeMediaControlListener() {
    if (_mediaControlListener != null) {
      MediaControlEventBus.instance.removeListener(_mediaControlListener!);
      _mediaControlListener = null;
    }
  }

  /// 处理播放/暂停
  void _handlePlayPause() async {
    if (_videoController!.value.isPlaying) {
      await _videoController!.pause();
    } else {
      await _videoController!.play();
    }
    setState(() {
      _isPlaying = _videoController!.value.isPlaying;
    });
  }

  /// 处理停止
  void _handleStop() async {
    await _videoController!.pause();
    await _videoController!.seekTo(Duration.zero);
    setState(() {
      _isPlaying = false;
    });
  }

  /// 处理快退
  void _handleRewind() async {
    final currentPosition = _videoController!.value.position;
    final newPosition = currentPosition - const Duration(seconds: 10);
    await _videoController!.seekTo(newPosition > Duration.zero ? newPosition : Duration.zero);
  }

  /// 处理快进
  void _handleFastForward() async {
    final currentPosition = _videoController!.value.position;
    final duration = _videoController!.value.duration;
    final newPosition = currentPosition + const Duration(seconds: 10);
    if (duration != null && newPosition < duration) {
      await _videoController!.seekTo(newPosition);
    } else if (duration != null) {
      await _videoController!.seekTo(duration);
    }
  }

  /// 处理音量增加
  void _handleVolumeUp() async {
    final currentVolume = _videoController!.value.volume;
    final newVolume = (currentVolume + 0.1).clamp(0.0, 1.0);
    await _videoController!.setVolume(newVolume);
  }

  /// 处理音量减少
  void _handleVolumeDown() async {
    final currentVolume = _videoController!.value.volume;
    final newVolume = (currentVolume - 0.1).clamp(0.0, 1.0);
    await _videoController!.setVolume(newVolume);
  }

  /// 处理静音
  void _handleMute() async {
    final currentVolume = _videoController!.value.volume;
    if (currentVolume > 0) {
      await _videoController!.setVolume(0.0);
    } else {
      await _videoController!.setVolume(1.0);
    }
  }

  Future<void> _initializeVideoPlayer() async {
    try {
      final videoUrl = await _getVideoUrl();
      if (videoUrl == null) {
        throw Exception('无法获取视频URL');
      }

      print('视频播放URL: $videoUrl');
      final videoFormat = _detectVideoFormat(videoUrl);
      _currentVideoUrl = videoUrl;
      _isLiveStream = _detectIsLiveStream(videoUrl);
      print('检测到视频格式: $videoFormat');
      
      VideoPlayerController controller;
      
      // 根据视频格式选择不同的控制器
      if (videoFormat == 'flv') {
        // FLV格式需要特殊处理，使用网络URL控制器
        // 在Windows平台上，FLV格式可能需要外部播放器支持
        controller = VideoPlayerController.networkUrl(Uri.parse(videoUrl));
        print('初始化FLV播放器 - Windows平台可能需要额外编解码器支持');
      } else if (videoFormat == 'm3u8') {
        // M3U8格式（HLS直播流）
        controller = VideoPlayerController.networkUrl(Uri.parse(videoUrl));
        print('初始化HLS直播流播放器');
      } else {
        // 其他格式使用标准网络URL控制器
        controller = VideoPlayerController.networkUrl(Uri.parse(videoUrl));
      }
      
      // 添加错误监听器
      controller.addListener(() {
        if (controller.value.hasError) {
          print('视频播放错误: ${controller.value.errorDescription}');
          // 对于FLV格式，可能需要特殊错误处理
          if (videoFormat == 'flv') {
            print('FLV格式可能需要外部播放器支持');
            // 在Windows平台上，FLV格式通常需要额外编解码器
            print('建议: 尝试使用MP4或M3U8格式的链接');
          }
        }
      });
      
      await controller.initialize().timeout(const Duration(seconds: 15));
      controller.addListener(() {
        if (mounted) setState(() {});
      });

      if (!mounted) return;

      setState(() {
        _videoController = controller;
        _chewieController = ChewieController(
          videoPlayerController: controller,
          autoPlay: true,
          looping: false,
          allowFullScreen: true,
          allowPlaybackSpeedChanging: true,
          showControls: true,
          customControls: _NbaControls(
            isLive: _isLiveStream,
            currentQuality: _currentQuality,
            qualities: _qualities,
            onChangeQuality: _changeQuality,
          ),
          materialProgressColors: ChewieProgressColors(
            playedColor: Colors.blue,
            handleColor: Colors.blue,
            backgroundColor: Colors.grey,
            bufferedColor: Colors.grey,
          ),
          errorBuilder: (context, errorMessage) {
            // 根据格式提供不同的错误提示
            String errorText;
            if (videoFormat == 'flv') {
              errorText = 'FLV格式播放失败\nWindows平台需要安装FLV编解码器\n错误信息: $errorMessage\n\n建议: 尝试使用MP4或M3U8格式的链接';
            } else if (videoFormat == 'm3u8') {
              errorText = '直播流播放失败: $errorMessage';
            } else {
              errorText = '视频播放失败: $errorMessage';
            }
            
            return Center(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(
                  errorText,
                  style: const TextStyle(color: Colors.white, fontSize: 14),
                  textAlign: TextAlign.center,
                ),
              ),
            );
          },
        );
        _showThumbnail = false;
        _isPlaying = true;
      });
      _chewieController!.addListener(() {
        final fs = _chewieController!.isFullScreen;
        if (mounted && fs != _isFullScreen) {
          setState(() {
            _isFullScreen = fs;
          });
        }
        if (_chewieController!.isPlaying != _isPlaying) {
          setState(() {
            _isPlaying = _chewieController!.isPlaying;
          });
        }
      });
    } on TimeoutException {
      if (mounted) {
        setState(() {
          _showThumbnail = true;
        });
      }
      print('视频初始化超时');
    } catch (e) {
      if (mounted) {
        setState(() {
          _showThumbnail = true;
        });
      }
      print('视频播放器初始化失败: $e');
      
      // 如果是FLV格式失败，记录特殊错误信息
      final videoFormat = _detectVideoFormat(await _getVideoUrl() ?? '');
      if (videoFormat == 'flv') {
        print('FLV格式在Windows平台播放失败，建议:');
        print('1. 安装Windows FLV编解码器包');
        print('2. 使用MP4或M3U8格式的链接替代');
        print('3. 考虑使用跨平台视频播放器如fvp包');
      }
    }
  }

  /// 检测视频格式
  String _detectVideoFormat(String url) {
    final uri = Uri.tryParse(url);
    if (uri == null) return 'unknown';
    
    final path = uri.path.toLowerCase();
    if (path.endsWith('.m3u8') || url.contains('.m3u8')) {
      return 'm3u8';
    } else if (path.endsWith('.flv') || url.contains('.flv')) {
      return 'flv';
    } else if (path.endsWith('.mp4') || url.contains('.mp4')) {
      return 'mp4';
    } else if (url.contains('.ts') || url.contains('m3u8')) {
      return 'm3u8';
    }
    
    // 根据URL模式猜测格式
    if (url.contains('/hls/') || url.contains('/live/')) {
      return 'm3u8';
    }
    
    return 'unknown';
  }

  bool _detectIsLiveStream(String url) {
    final u = url.toLowerCase();
    if (u.contains('/live/')) return true;
    return false;
  }

  Future<String?> _getVideoUrl() async {
    // 根据视频ID获取播放URL
    // 使用NBA官方API获取真实的播放URL
    if (widget.vid.isNotEmpty) {
      final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      final apiUrl = 'https://api.nba.cn/cms/v1/video/playurl?app_key=tiKB2tNdncnZFPOi&app_version=1.1.0&channel=NBA&device_id=c263274b75182ba88d82184208ee88a2&install_id=2023821643&network=N%2FA&os_type=3&os_version=1.0.0&quality=${_currentQuality}&sign=sign_v2&sign2=0576745EB1E18C8BA6BDCB1744B0FF5FE30A6FAD7589D951D2185E102FF88011&t=$timestamp&vid=${widget.vid}';
      
      try {
        final response = await http.get(Uri.parse(apiUrl));
        if (response.statusCode == 200) {
          final jsonData = json.decode(response.body);
          if (jsonData['code'] == 0 && jsonData['data'] != null) {
            // 更新清晰度列表（如果API返回了清晰度信息）
            if (jsonData['data']['qualities'] != null && _qualities.isEmpty) {
              setState(() {
                _qualities = List<Map<String, String>>.from(jsonData['data']['qualities']);
              });
            }
            // 返回真实的视频播放URL
            return jsonData['data']['url']?.toString();
          }
        }
      } catch (e) {
        print('获取视频播放地址失败: $e');
      }
      
      // 如果API调用失败，返回构造的API URL作为fallback
      return apiUrl;
    }
    
    // 如果有完整的视频数据，尝试其他可能的URL字段
    if (widget.videoData != null) {
      // 优先尝试flv格式的URL
      final flvUrl = widget.videoData!['flv_url']?.toString();
      if (flvUrl != null && flvUrl.isNotEmpty) {
        return flvUrl;
      }
      
      // 优先尝试m3u8格式的URL
      final m3u8Url = widget.videoData!['m3u8_url']?.toString();
      if (m3u8Url != null && m3u8Url.isNotEmpty) {
        return m3u8Url;
      }
      
      // 尝试mp4格式的URL
      final mp4Url = widget.videoData!['mp4_url']?.toString();
      if (mp4Url != null && mp4Url.isNotEmpty) {
        return mp4Url;
      }
      
      // 尝试其他可能的视频URL字段
      final sourceUrl = widget.videoData!['source_url']?.toString();
      if (sourceUrl != null && sourceUrl.isNotEmpty) {
        return sourceUrl;
      }
      
      final newSourceUrl = widget.videoData!['new_source_url']?.toString();
      if (newSourceUrl != null && newSourceUrl.isNotEmpty) {
        return newSourceUrl;
      }
    }
    
    return null;
  }

  String _getThumbnailUrl() {
    // 获取缩略图URL
    if (widget.videoData != null) {
      final imageUrl = widget.videoData!['image']?.toString();
      if (imageUrl != null && imageUrl.isNotEmpty) {
        return imageUrl;
      }
      
      // 如果没有image字段，尝试其他可能的缩略图字段
      final thumbnailY = widget.videoData!['thumbnail_y']?.toString();
      if (thumbnailY != null && thumbnailY.isNotEmpty) {
        return 'https://img.nba.cn$thumbnailY';
      }
    }
    
    // 如果没有视频数据，返回默认的NBA视频缩略图
    return 'https://img.nba.cn/image/nms/wsc/default_video_thumb.jpg';
  }

  String _getVideoTitle() {
    return widget.title.isNotEmpty ? widget.title : 'NBA视频';
  }

  String _getVideoDuration() {
    if (widget.videoData != null) {
      final duration = widget.videoData!['duration'];
      if (duration != null) {
        final minutes = (duration ~/ 60).toString().padLeft(2, '0');
        final seconds = (duration % 60).toString().padLeft(2, '0');
        return '$minutes:$seconds';
      }
    }
    return '';
  }

  @override
  void dispose() {
    _videoController?.dispose();
    _chewieController?.dispose();
    _removeMediaControlListener();
    _controlsTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: Colors.grey[100],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 视频标题
          if (_getVideoTitle().isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(12, 12, 12, 8),
              child: Text(
                _getVideoTitle(),
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          
          // 视频播放器或缩略图
          AspectRatio(
            aspectRatio: widget.aspectRatio,
            child: _showThumbnail
                ? _buildThumbnail()
                : _buildVideoPlayer(),
          ),
          
          // 底部信息去除
          const SizedBox.shrink(),
        ],
      ),
    );
  }

  Widget _buildThumbnail() {
    final thumbnailUrl = _getThumbnailUrl();
    
    return GestureDetector(
      onTap: _initializeVideoPlayer,
      child: Stack(
        fit: StackFit.expand,
        children: [
          if (thumbnailUrl.isNotEmpty)
            CachedNetworkImage(
              imageUrl: thumbnailUrl,
              fit: BoxFit.cover,
              placeholder: (context, url) => Container(
                color: Colors.grey[200],
                child: const Icon(Icons.videocam, color: Colors.grey, size: 48),
              ),
              errorWidget: (context, url, error) => Container(
                color: Colors.grey[200],
                child: const Icon(Icons.error, color: Colors.grey, size: 48),
              ),
            )
          else
            Container(
              color: Colors.grey[200],
              child: const Icon(Icons.videocam, color: Colors.grey, size: 48),
            ),
          
          // 播放按钮
          const Center(
            child: CircleAvatar(
              radius: 24,
              backgroundColor: Colors.black54,
              child: Icon(
                Icons.play_arrow,
                color: Colors.white,
                size: 32,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildQualitySelector() {
    return PopupMenuButton<String>(
      icon: const Icon(Icons.hd, size: 16, color: Colors.grey),
      tooltip: '选择清晰度',
      onSelected: _changeQuality,
      itemBuilder: (BuildContext context) {
        return _qualities.map<PopupMenuEntry<String>>((quality) {
          final qualityName = quality['name']?.toString() ?? '';
          final qualityDisplayName = quality['sname']?.toString() ?? qualityName;
          
          return PopupMenuItem<String>(
            value: qualityName,
            child: Row(
              children: [
                if (_currentQuality == qualityName)
                  const Icon(Icons.check, size: 16, color: Colors.blue),
                const SizedBox(width: 8),
                Text(qualityDisplayName),
              ],
            ),
          );
        }).toList();
      },
    );
  }

  Widget _buildVideoPlayer() {
    if (_chewieController == null || _videoController == null) {
      return Container(
        color: Colors.black,
        constraints: const BoxConstraints.expand(),
        child: const Center(
          child: CircularProgressIndicator(
            color: Colors.blue,
          ),
        ),
      );
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        if (constraints.maxWidth.isFinite && constraints.maxHeight.isFinite) {
          return Chewie(controller: _chewieController!);
        } else {
          return Container(
            color: Colors.black,
            child: const Center(
              child: Text('视频尺寸无效', style: TextStyle(color: Colors.white)),
            ),
          );
        }
      },
    );
  }

  String _formatTimeLabel() {
    final pos = _videoController?.value.position ?? Duration.zero;
    final dur = _videoController?.value.duration ?? Duration.zero;
    String fmt(Duration d) {
      final m = d.inMinutes.remainder(60).toString().padLeft(2, '0');
      final s = d.inSeconds.remainder(60).toString().padLeft(2, '0');
      final h = d.inHours;
      return h > 0 ? '$h:$m:$s' : '$m:$s';
    }
    return '${fmt(pos)} / ${fmt(dur)}';
  }

  Widget _buildQualitySelectorOverlay() {
    return PopupMenuButton<String>(
      icon: const Icon(Icons.hd, size: 18, color: Colors.white),
      tooltip: '选择清晰度',
      onSelected: _changeQuality,
      itemBuilder: (BuildContext context) {
        return _qualities.map<PopupMenuEntry<String>>((quality) {
          final qualityName = quality['name']?.toString() ?? '';
          final qualityDisplayName = quality['sname']?.toString() ?? qualityName;
          return PopupMenuItem<String>(
            value: qualityName,
            child: Row(
              children: [
                if (_currentQuality == qualityName)
                  const Icon(Icons.check, size: 16, color: Colors.blue),
                const SizedBox(width: 8),
                Text(qualityDisplayName),
              ],
            ),
          );
        }).toList();
      },
    );
  }
}


class _NbaControls extends StatefulWidget {
  final bool isLive;
  final String currentQuality;
  final List<Map<String, dynamic>> qualities;
  final ValueChanged<String> onChangeQuality;
  const _NbaControls({
    required this.isLive,
    required this.currentQuality,
    required this.qualities,
    required this.onChangeQuality,
  });

  @override
  State<_NbaControls> createState() => _NbaControlsState();
}

class _NbaControlsState extends State<_NbaControls> {
  ChewieController? _chewieController;
  bool _isPlaying = false;
  bool _showVolume = false;
  double _volume = 1.0;
  VideoPlayerController? _vpc;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_chewieController == null) {
      _chewieController = ChewieController.of(context);
      _isPlaying = _chewieController!.isPlaying;
      _volume = _chewieController!.videoPlayerController.value.volume;
      _chewieController!.addListener(_updatePlayState);
      _vpc = _chewieController!.videoPlayerController;
      _vpc!.addListener(_onVideoValueChanged);
    }
  }

  @override
  void dispose() {
    _chewieController?.removeListener(_updatePlayState);
    _vpc?.removeListener(_onVideoValueChanged);
    super.dispose();
  }

  void _updatePlayState() {
    if (!mounted) return;
    final playing = _chewieController!.isPlaying;
    if (_isPlaying != playing) {
      setState(() {
        _isPlaying = playing;
      });
    }
  }

  void _onVideoValueChanged() {
    if (!mounted) return;
    setState(() {});
  }

  String _format(Duration d) {
    final m = d.inMinutes.remainder(60).toString().padLeft(2, '0');
    final s = d.inSeconds.remainder(60).toString().padLeft(2, '0');
    final h = d.inHours;
    return h > 0 ? '$h:$m:$s' : '$m:$s';
  }

  @override
  Widget build(BuildContext context) {
    final v = _chewieController!.videoPlayerController.value;
    final pos = v.position;
    final dur = v.duration;
    final isFs = _chewieController!.isFullScreen;
    return LayoutBuilder(
      builder: (context, constraints) {
        final w = constraints.maxWidth.isFinite ? constraints.maxWidth : MediaQuery.of(context).size.width;
        final h = constraints.maxHeight.isFinite ? constraints.maxHeight : MediaQuery.of(context).size.height;
        final base = 640.0;
        final scale = (w / base).clamp(0.7, 1.3);
        final iconSize = 22.0 * scale;
        final smallIconSize = 18.0 * scale;
        final textSize = 12.0 * scale;
        final volumeSliderWidth = (120.0 * scale).clamp(90.0, 160.0);
        return Container(
          color: Colors.transparent,
          child: Stack(
            children: [
              Positioned(
                left: 8,
                right: 8,
                bottom: 8,
                child: Row(
                  children: [
                    IconButton(
                      icon: Icon(
                        _isPlaying ? Icons.pause : Icons.play_arrow,
                        color: Colors.white,
                        size: iconSize,
                      ),
                      onPressed: () async {
                        final playing = _chewieController!.isPlaying;
                        if (playing) {
                          await _chewieController!.videoPlayerController.pause();
                          _chewieController!.pause();
                          _isPlaying = false;
                        } else {
                          await _chewieController!.videoPlayerController.play();
                          _chewieController!.play();
                          _isPlaying = true;
                        }
                        if (mounted) setState(() {});
                      },
                    ),
                    if (!widget.isLive) ...[
                      const SizedBox(width: 6),
                      Text(
                        '${_format(pos)} / ${_format(dur)}',
                        style: TextStyle(color: Colors.white, fontSize: textSize),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: SliderTheme(
                          data: SliderTheme.of(context).copyWith(
                            trackHeight: 2.0 * scale,
                            thumbShape: RoundSliderThumbShape(enabledThumbRadius: 6.0 * scale),
                          ),
                          child: Slider(
                            min: 0,
                            max: dur.inMilliseconds.toDouble(),
                            value: pos.inMilliseconds
                                .clamp(0, dur.inMilliseconds)
                                .toDouble(),
                            activeColor: Colors.blue,
                            onChanged: (v) async {
                              final d = Duration(milliseconds: v.round());
                              await _chewieController!.videoPlayerController.seekTo(d);
                            },
                          ),
                        ),
                      ),
                    ],
                    const SizedBox(width: 8),
                    IconButton(
                      icon: Icon(
                        _volume <= 0 ? Icons.volume_off : Icons.volume_up,
                        color: Colors.white,
                        size: smallIconSize,
                      ),
                      onPressed: () async {
                        if (_volume > 0) {
                          _volume = 0.0;
                        } else {
                          _volume = 1.0;
                        }
                        await _chewieController!.videoPlayerController.setVolume(_volume);
                        if (mounted) setState(() {});
                      },
                    ),
                    if (_showVolume)
                      SizedBox(
                        width: volumeSliderWidth,
                        child: SliderTheme(
                          data: SliderTheme.of(context).copyWith(
                            trackHeight: 2.0 * scale,
                            thumbShape: RoundSliderThumbShape(enabledThumbRadius: 6.0 * scale),
                          ),
                          child: Slider(
                            min: 0,
                            max: 1,
                            divisions: 10,
                            value: _volume,
                            activeColor: Colors.blue,
                            onChanged: (val) async {
                              _volume = val;
                              await _chewieController!.videoPlayerController.setVolume(_volume);
                              if (mounted) setState(() {});
                            },
                          ),
                        ),
                      ),
                    IconButton(
                      icon: Icon(Icons.tune, color: Colors.white, size: smallIconSize),
                      onPressed: () {
                        setState(() {
                          _showVolume = !_showVolume;
                        });
                      },
                    ),
                    PopupMenuButton<String>(
                      icon: Icon(Icons.hd, size: smallIconSize, color: Colors.white),
                      tooltip: '选择清晰度',
                      onSelected: (q) {
                        widget.onChangeQuality(q);
                      },
                      itemBuilder: (BuildContext context) {
                        return widget.qualities.map<PopupMenuEntry<String>>((quality) {
                          final qualityName = quality['name']?.toString() ?? '';
                          final qualityDisplayName = quality['sname']?.toString() ?? qualityName;
                          return PopupMenuItem<String>(
                            value: qualityName,
                            child: Row(
                              children: [
                                if (widget.currentQuality == qualityName)
                                  const Icon(Icons.check, size: 16, color: Colors.blue),
                                const SizedBox(width: 8),
                                Text(qualityDisplayName),
                              ],
                            ),
                          );
                        }).toList();
                      },
                    ),
                    const SizedBox(width: 8),
                    IconButton(
                      icon: Icon(isFs ? Icons.fullscreen_exit : Icons.fullscreen,
                          color: Colors.white, size: iconSize),
                      onPressed: () {
                        final fs = _chewieController!.isFullScreen;
                        if (fs) {
                          _chewieController!.exitFullScreen();
                        } else {
                          _chewieController!.enterFullScreen();
                        }
                        setState(() {});
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
